﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Common
{
    public class HttpSecurity
    {
        /// <summary>  
        /// 加密  
        /// </summary>  
        /// <param name="str">要加密的</param>  
        /// <param name="key">钥匙</param>  
        /// <returns></returns>  
        public static string Encode(string str, string key)
        {
            System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            MemoryStream stream = new MemoryStream();
            System.Security.Cryptography.CryptoStream stream2 = new System.Security.Cryptography.CryptoStream(stream, provider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            stream2.Write(bytes, 0, bytes.Length);
            stream2.FlushFinalBlock();
            StringBuilder builder = new StringBuilder();
            foreach (byte num in stream.ToArray())
            {
                builder.AppendFormat("{0:X2}", num);
            }
            stream.Close();
            return builder.ToString();
        }

        /// <summary>  
        /// 解密  
        /// </summary>  
        /// <param name="str">要解密的</param>  
        /// <param name="key">钥匙</param>  
        /// <returns></returns>  
        public static string Decode(string str, string key)
        {
            System.Security.Cryptography.DESCryptoServiceProvider provider = new System.Security.Cryptography.DESCryptoServiceProvider();
            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));
            byte[] buffer = new byte[str.Length / 2];
            for (int i = 0; i < (str.Length / 2); i++)
            {
                int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
                buffer[i] = (byte)num2;
            }
            MemoryStream stream = new MemoryStream();
            System.Security.Cryptography.CryptoStream stream2 = new System.Security.Cryptography.CryptoStream(stream, provider.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            stream2.Write(buffer, 0, buffer.Length);
            stream2.FlushFinalBlock();
            stream.Close();
            return Encoding.GetEncoding("UTF-8").GetString(stream.ToArray());
        }
    }
}
